<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 29/08/2017
 * Time: 17:36
 */
namespace backend\controllers;

use backend\models\OnlyCaptchaValidate;
use common\models\ar\User;
use common\models\Common;
//use common\models\LoginForm;
use common\models\Sms;
use yii\web\Controller;
use yii\web\Cookie;
use common\models\ar\UserBrokers;
use common\models\ar\ChangeCache;
class RegController extends Controller
{
    public $layout = 'login';

    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'common\actions\CaptchaAction',
                'minLength' => 4,
                'maxLength' => 4,
                'transparent' => true,
                'offset' => 8,
                'padding' => 1,
            ],
        ];
    }

    public function actionIndex()
    {
        $req = \Yii::$app->request;
        $res = \Yii::$app->response;
        $brokerId = trim($req->get('recommend_code', ''));
        if (!$brokerId) {
            //从cookie中查看是否有记录
            $brokerId = $req->cookies->getValue('brokerId', '');
        }

        $pObj = User::find()->where(['loginName' =>$brokerId])->one();
        if ($pObj && $pObj->login_flag != 1) {
            //将推荐码保存到cookie中，防止页面跳转时不能正确识别来源
            $cookie = new Cookie([
                'name' => 'brokerId',
                'value' => $brokerId,
                'expire' => time() + 5 * 60,//保留5分钟,
                'httpOnly' => true,
            ]);
            $res->cookies->add($cookie);
        } else {
            //输入了不存在的推荐码，删除
            $res->cookies->remove('brokerId');
            //将推荐码置为空
            $brokerId = '';
        }

        return $this->render('index', ['brokerId' => $brokerId]);
    }

    public function actionSubmit()
    {
        $agentID = '0';
        $levelId = '01';
        $req = \Yii::$app->request;
        if ($req->post('field＿name')){
            $agentID = $req->post('field＿name');
            $userBrokers = UserBrokers::find()->where(['id' => $agentID])->one();
            if ($userBrokers){
                $agentID = $userBrokers['id'];
                $levelId = (string)($userBrokers['level']+1);
            }
        }
        else
        {
            $code = trim($req->post("code", ''));
            if (empty($code)) {
                $code = 1001;
                $msg = "请输入邀请码";
                exit(json_encode(['code' => $code, 'msg' => $msg]));
            }
            $codes=UserBrokers::findOne(["id"=>$code]);
            if (!$codes){
                $code = 1001;
                $msg = "您输入邀请码不存在";
                exit(json_encode(['code' => $code, 'msg' => $msg]));
            }else{
                $levelId=(string)($codes['level']+1);
                $agentID = $codes['id'];
            }
        }

        $alias = trim($req->post("alias", ''));
        if (mb_strlen($alias) < 2) {
            $code = 1001;
            $msg = "请输入您的真实姓名";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        $password = trim($req->post("password", ''));
        if (strlen($password) < 6) {
            $code = 1003;
            $msg = '密码长度不能小于6位';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $captcha = trim(\Yii::$app->request->post('captcha', ''));
        $validate = new OnlyCaptchaValidate();
        $validate->controller = 'reg';
        $validate->captcha = $captcha;

        if (!$validate->validate()) {
            exit(json_encode(['code' => 1001, 'msg' => "验证码不正确 "]));
        }

        //创建交易账户
        $time=date("Y-m-d H:i:s");
        if (strlen($levelId) < 2) {
            $num = str_pad($levelId, 2, "0", STR_PAD_LEFT);
        }else{
            $num=$levelId;
        }
        $clientSN ='1242';
        $clientSN ="6{$num}{$clientSN}";
        $clientLike = "6{$num}%";
        $userTmp = "SELECT `loginName` FROM `user_brokers` WHERE loginName like '".$clientLike."' ORDER BY `loginName` DESC LIMIT 1";
        $userTmp = User::findBySql($userTmp)->one();
        if($userTmp)
        {
            $clientSN=(string)($userTmp['loginName']+1);
        }
        try{
            $UserBrokers=new UserBrokers();
            $UserBrokers->loginName=$clientSN;
            $UserBrokers->loginPsw =$password;
            $UserBrokers->accountName =$alias;
            $UserBrokers->level = $levelId;
            $UserBrokers->upperLevelId=$agentID;
            $UserBrokers->templateId ='';
            $UserBrokers->addDate = $time;
            $UserBrokers->save();
            $UserIDs=UserBrokers::find()->where(['loginName'=>$clientSN])->one();
            $Changecaches = new Changecache;
            $Changecaches->userid=$UserIDs['id'];
            $Changecaches->change_type=3;
            $Changecaches->save();
        }catch(Exception $e){
            echo "False hints";
        }
        if ($UserBrokers->save()){
            $code = 1;
            $msg = "创建成功";
            setcookie("login_clientSN", $clientSN, time() + 7 * 24 * 3600, '/');
        }else{
            $code = 0;
            $msg = "创建失败";
        }
        exit(json_encode(['code' => $code, 'msg' => $msg]));
    }

    /**
     * 发送短信
     */
    public function actionSendSms()
    {
        $cellphone = trim(\Yii::$app->request->get('cellphone', ''));
        $captcha = trim(\Yii::$app->request->get('captcha', ''));
        $recommendCode = trim(\Yii::$app->request->get('recommend_code', ''));

        $validate = new OnlyCaptchaValidate();
        $validate->controller = 'reg';
        $validate->captcha = $captcha;

        if (!$validate->validate()) {
            exit(json_encode(['code' => 1001, 'msg' => "验证码不正确 "]));
        }

        $sql = "SELECT * FROM `user` WHERE `recommend_code` = :recommend_code AND `level` != 4";
        $pObj = User::findBySql($sql, [":recommend_code" => $recommendCode])->one();
        if (!$pObj || $pObj->login_flag == 0) {
            $code = 1002;
            $msg = '推荐码不存在';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $check = Common::dataCheck($cellphone, [
            'type' => 3,
            'detail' => [
                'pattern' => '/^1[34578][0-9]{9}$/',
                'info' => '手机号码不正确'
            ],
        ]);
        if ($check['code'] != 1) {
            $code = 1003;
            $msg = $check['msg'];
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        //一个手机号只能绑定一个账号
        $levelInfo = Common::getLevelsInfo($pObj->level);
        $isExist = User::find()->where(['cellphone' => $cellphone, 'level' => $levelInfo['cid']])->count();
        if ($isExist) {
            $code = 1004;
            $msg = '手机号码已绑定';
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }

        $return = Sms::send($cellphone, 1);
        exit(json_encode($return));
    }

        /**
     * 注册信息显示
     */
    public function actionInfo()
    {
        $uid=$_COOKIE["login_clientSN"];
        $userObj = UserBrokers::findOne(['loginName'=>$uid]);
        return $this->render('info', ['info' => $userObj]);
    }

}